<template>
  <div class="j-editor-container">
    <Tinymce 
      v-model:value="innerValue" 
      :height="height" 
      :disabled="disabled"
      :auto-focus="autoFocus"
      :plugins="plugins"
      :toolbar="toolbar"
      @change="onChange" 
    />
    <div v-if="showFileUploadBtn" class="file-upload-btn">
      <a-upload
        name="file"
        :action="uploadUrl"
        :headers="headers"
        :data="uploadData"
        :showUploadList="false"
        :beforeUpload="beforeUpload"
        @change="handleFileChange"
      >
        <a-button type="primary" :disabled="disabled">
          <upload-outlined />
          上传附件
        </a-button>
      </a-upload>
    </div>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, nextTick, ref, watch } from 'vue';
  import { Tinymce } from '/@/components/Tinymce';
  import { propTypes } from '/@/utils/propTypes';
  import { Form, Upload, Button, message } from 'ant-design-vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getHeaders, getFileAccessHttpUrl } from '/@/utils/common/compUtils';

  // 新增本地静态资源URL生成函数
  function buildStaticUrl(dbPath) {
    if (!dbPath) return '';
    if (dbPath.startsWith('/')) dbPath = dbPath.substring(1);
    return `/sys/common/static/${dbPath}`;
  }

  export default defineComponent({
    name: 'JEditor',
    // 不将 attrs 的属性绑定到 html 标签上
    inheritAttrs: false,
    components: { 
      Tinymce, 
      AUpload: Upload, 
      AButton: Button,
      UploadOutlined
    },
    props: {
      value: propTypes.string.def(''),
      disabled: propTypes.bool.def(false),
      //是否聚焦
      autoFocus: propTypes.bool.def(true),
      // 编辑器高度
      height: propTypes.number.def(300),
      // 是否显示文件上传按钮
      showFileUploadBtn: propTypes.bool.def(true),
    },
    emits: ['change', 'update:value'],
    setup(props, { emit, attrs }) {
      const innerValue = ref(props.value || '');
      const formItemContext = Form.useInjectFormItemContext();
      const { domainUrl } = useGlobSetting();
      
      // 文件上传URL - 使用完整的URL路径
      // 确保domainUrl末尾没有斜杠，uploadPath开头有斜杠
      const uploadPath = '/sys/fileRecord/uploadRichTextFile';

      // 检查domainUrl是否包含上下文路径
      let uploadUrl = '';
      // 获取当前页面的上下文路径
      const currentPath = window.location.pathname;
      const contextPath = currentPath.substring(0, currentPath.indexOf('/', 1) || 0);
      console.log('当前上下文路径:', contextPath);

      if (domainUrl.includes('/jeecg-boot')) {
        // 如果domainUrl已经包含上下文路径
        uploadUrl = domainUrl + uploadPath;
      } else if (contextPath && contextPath !== '/') {
        // 如果当前页面有上下文路径
        uploadUrl = domainUrl + contextPath + uploadPath;
      } else {
        // 默认添加/jeecg-boot
        uploadUrl = domainUrl + '/jeecg-boot' + uploadPath;
      }

      console.log('文件上传URL:', uploadUrl);
      console.log('域名URL:', domainUrl);
      console.log('当前页面URL:', window.location.href);
      console.log('当前页面路径:', window.location.pathname);

      // 请求头
      const headers = getHeaders();
      console.log('请求头:', headers);
      
      // 上传参数
      const uploadData = {
        biz: 'richtext',
        type: 'attachment'
      };
      
      // 编辑器插件
      const plugins = 'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount';
      
      // 编辑器工具栏
      const toolbar = 'bold italic underline strikethrough alignleft aligncenter alignright outdent indent blockquote undo redo removeformat subscript superscript code codesample hr bullist numlist link image charmap preview anchor pagebreak insertdatetime table emoticons forecolor backcolor fullscreen';
      
      // 监听props.value变化
      watch(
        () => props.value,
        (val) => {
          if (val !== innerValue.value) {
            innerValue.value = val || '';
          }
        }
      );
      
      // 监听innerValue变化
      watch(
        () => innerValue.value,
        (val) => {
          emit('update:value', val);
          emit('change', val);
          // 触发表单验证
        nextTick(() => {
          formItemContext?.onFieldChange();
        });
        }
      );
      
      // 内容变化事件
      function onChange(value) {
        innerValue.value = value;
      }
      
      // 上传前校验
      function beforeUpload(file) {
        // 检查文件大小（10MB限制）
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          message.error('文件大小不能超过10MB!');
          return false;
        }
        
        // 检查文件类型
        const fileName = file.name;
        const extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        const allowedTypes = [
          // 图片
          'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',
          // 文档
          'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt',
          // 音频
          'mp3', 'wav', 'ogg', 'flac', 'aac',
          // 视频
          'mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'
        ];
        
        if (!allowedTypes.includes(extension)) {
          message.error('不支持的文件类型!');
          return false;
        }
        
        return true;
      }
      
      // 文件上传状态变化处理
      function handleFileChange(info) {
        if (info.file.status === 'uploading') {
          message.loading({ content: '文件上传中...', key: 'fileUpload' });
        }
        if (info.file.status === 'done') {
          message.success({ content: '文件上传成功!', key: 'fileUpload', duration: 2 });
          if (info.file.response && info.file.response.success) {
            const fileName = info.file.name;
            const dbPath = info.file.response.result;
            const extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
            let url = buildStaticUrl(dbPath);
            let content = '';
            if (["jpg","jpeg","png","gif","bmp","webp"].includes(extension)) {
              content = `<img src="${url}" alt="${fileName}" style="max-width: 100%;" />`;
            } else if (["mp3","wav","ogg","flac","aac"].includes(extension)) {
              content = `<audio controls><source src="${url}" type="audio/${extension}">您的浏览器不支持音频播放</audio>`;
            } else if (["mp4","avi","mov","wmv","flv","mkv"].includes(extension)) {
              content = `<video controls width="320" height="240"><source src="${url}" type="video/${extension}">您的浏览器不支持视频播放</video>`;
            } else if (["pdf"].includes(extension)) {
              content = `<a href="${url}" target="_blank">预览PDF</a>`;
            } else {
              content = `<a href="${url}" target="_blank" download="${fileName}">${fileName}</a>`;
            }
            innerValue.value = innerValue.value + content;
          }
        }
        if (info.file.status === 'error') {
          message.error({ content: '文件上传失败!', key: 'fileUpload' });
        }
      }

      return {
        innerValue,
        onChange,
        uploadUrl,
        headers,
        uploadData,
        beforeUpload,
        handleFileChange,
        plugins,
        toolbar,
      };
    },
  });
</script>

<style lang="less" scoped>
.j-editor-container {
  position: relative;
  width: 100%;
  
  .file-upload-btn {
    margin-top: 8px;
  }
}
</style>
